
/* web socket */
var ws = function () {
    var channel = getUrlParam('channel');
    if (channel == null && window.block != null)
        channel = window.block === '' ? '[ROOT]' : window.block;
    if (!channel)
        channel = prompt('请输入聊天频道');
    if (!channel){
        alert('频道必填');
        history.go(0);
    }
    $('.channel').text(channel);
    var user= window.user || prompt('请输入您的姓名');
    if (!user){
        alert('姓名必填');
        history.go(0);
    }
    //连接socket后端服务器
    var socket=io.connect((window.useSSL ? "wss" : "ws") + "://"+window.location.hostname+":" + window.wsPort);
    //通知用户有用户登录
    socket.emit('signin',{channel,user});
    //监听新用户登录
    socket.on('signin',function (o) {
        updateMsg(o, 'signin');
    });
    //监听用户退出
    socket.on('signout',function (o) {
        updateMsg(o, 'signout');
    });
    //接收其他人发来的消息
    socket.on('message',function (obj) {
        let msgHtml = '<section class="others">'
                +'<span>'+obj.user+'</span>'
                +'<div>'+obj.content+'</div>'
                +'</section>';
        $('.main-body').append(msgHtml);
        $('.main-body').scrollTop(99999);
    });
    //接收自己返还的消息
    socket.on('self-message',function (obj) {
        let msgHtml = '<section class="me">'
                +'<span>'+obj.user+'</span>'
                +'<div>'+obj.content+'</div>'
                +'</section>';
        $('.main-body').append(msgHtml);
        $('.main-body').scrollTop(99999);
    });
    //删除所有监听
    //socket.removeAllListeners('message');
    $('.send').click(function () {
        var content=$('input[name="msg"]').val();
        if (content){
            socket.emit('message',{user, content});
            $('input[name="msg"]').val("");
        }
    });
    $('input[name="msg"]').keypress(function(e){
        if (e.which===13) $('.send').click();
    })
};

window.onload = function () {
    setTimeout(ws, 100);
};

/*用户id生成*/
function  genUid() {
    return new Date().getTime()+""+Math.floor(Math.random()*899+100);
}
function signout(){
    socket.disconnect();
    location.reload();
}
/*监听函数*/
function updateMsg(o, action) {
    //更新在线人数
    let userList='';
    let sep = ', '
    for(let u of o.users){
        userList+=u+', ';
    }
    if (userList.substring(-(sep.length)) === sep)
        userList = userList.substr(0, userList.length - sep.length);

    //更新房间信息
    $('.chatNum').text(o.users.length);
    $('.chatList').text(userList);
    //系统消息
    let sysHtml='<section>Unrecognize system-action</section>';
    if(action==='signin'){
        sysHtml='<section class="chatRoomTip"><div>'+o.user+'进入聊天室</div></section>';
    }
    if(action==="signout"){
        sysHtml='<section class="chatRoomTip"><div>'+o.user+'退出聊天室</div></section>';
    }
    $(".main-body").append(sysHtml);
    $('.main-body').scrollTop(99999);
}